package com.uziot.bucket.mapper.config;

import com.github.dozermapper.core.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Shanks
 * @date 2020-10-30
 */
@Component
public class DozerConverter {

    @Autowired
    @Qualifier("dozerMapper")
    private Mapper mapper;

    public <T> void copyProperties(Object source, Class<T> destinationClass) {
        mapper.map(source, destinationClass);
    }

    public <T> T map(Object source, Class<T> destinationClass) {
        return mapper.map(source, destinationClass);
    }

    public <T> List<T> map(List<?> sourceList, Class<T> destinationClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return new ArrayList<>();
        }
        return sourceList.stream()
                .map(s -> mapper.map(s, destinationClass))
                .collect(Collectors.toList());
    }

    public <T> Set<T> map(Set<?> sourceSet, Class<T> destinationClass) {
        if (CollectionUtils.isEmpty(sourceSet)) {
            return new HashSet<>();
        }
        return sourceSet.stream()
                .map(s -> mapper.map(s, destinationClass))
                .collect(Collectors.toSet());
    }
}